<template>
  <basic-dialog v-model="visible" custom-class="no-footer" width="80%" :title="title" destroy-on-close
    @close="dialogClose">
    <el-container>
      <div id="entityRelation" style="width: 100%; height: 600px"></div>
    </el-container>
    <template #footer-right>
      <div>
        <el-button :type="curActive === 'relation' ? 'primary' : ''" @click="showLink">显示当前对象关联</el-button>
        <el-button :type="curActive === 'link' ? 'primary' : ''" @click="showLinkMe">显示引用当前对象</el-button>
      </div>
    </template>
  </basic-dialog>
</template>

<script setup>
import { apiGetEr, apiGetLinkMeEr } from '@/apis/objectModel/businessType'
import go from 'gojs'
const visible = ref(false)
const title = ref('')
const curActive = ref('relation')
const tabRelView = ref([])
const tabViewList = ref([])
let sourceData = {}
let myDiagram = {}
const show = (row) => {
  let elementById = document.getElementById('entityRelation')
  if (elementById) {
    elementById.innerHTML = ''
  }
  if (myDiagram) {
    myDiagram.div = null
    myDiagram = {}
  }
  curActive.value = 'relation'
  title.value = row.code + ' ' + row.name + '__关联的对象'
  visible.value = true
  sourceData = row
  tabRelView.value = []
  tabViewList.value = []
  apiGetEr(row.id).then((res) => {
    showNodes(res)
  })
}

const showNodes = (res) => {
  wrapperNode(res)
  const $ = go.GraphObject.make
  myDiagram = $(go.Diagram, 'entityRelation', {
    initialContentAlignment: go.Spot.Center,
    allowDelete: false,
    allowCopy: false,
    layout: $(go.ForceDirectedLayout),
    'undoManager.isEnabled': true,
  })

  myDiagram.nodeTemplate = $(
    go.Node,
    'Auto',
    {
      selectionAdorned: true,
      resizable: true,
      layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized,
      fromSpot: go.Spot.AllSides,
      toSpot: go.Spot.AllSides,
      isShadowed: true,
      shadowColor: '#CCAA',
    },
    new go.Binding('location', 'location').makeTwoWay(),
    new go.Binding('desiredSize', 'visible', function () {
      return new go.Size(NaN, NaN)
    }).ofObject('LIST'),
    $(
      go.Shape,
      'Rectangle',
      new go.Binding('fill', 'isHighlighted', function (h) {
        return h ? '#F44336' : '#A7E7FC'
      }).ofObject()
    ),
    $(
      go.Panel,
      'Table',
      { margin: 15, stretch: go.GraphObject.Fill },
      $(go.RowColumnDefinition, {
        row: 0,
        sizing: go.RowColumnDefinition.None,
      }),
      // the table header
      $(
        go.TextBlock,
        {
          row: 0,
          alignment: go.Spot.Center,
          margin: new go.Margin(0, 14, 0, 2), // leave room for Button
          font: 'bold 16px sans-serif',
        },
        new go.Binding('text', 'key')
      ),
      $(
        go.Panel,
        'Vertical',
        {
          name: 'LIST',
          row: 1,
          padding: 0, //表名到下边框的距离
          alignment: go.Spot.TopLeft,
          defaultAlignment: go.Spot.Left,
          stretch: go.GraphObject.Horizontal,
          //itemTemplate: itemTempl
        },
        new go.Binding('itemArray', 'items')
      )
    ) // end Table Panel
  ) // end Node

  // define the Link template, representing a relationship

  myDiagram.linkTemplate = $(
    go.Link, // the whole link panel
    {
      selectionAdorned: true,
      layerName: 'Foreground',
      reshapable: true,
      routing: go.Link.AvoidsNodes,
      corner: 5,
      curve: go.Link.JumpOver,
      toEndSegmentLength: 100,
    },
    $(
      go.Shape, // the link shape
      { stroke: '#303B45', strokeWidth: 2.5 }
    ),
    $(
      go.TextBlock, // the "from" label
      {
        textAlign: 'center',
        font: 'bold 14px sans-serif',
        stroke: '#1967B3',
        segmentIndex: 0,
        segmentOffset: new go.Point(NaN, NaN),
        segmentOrientation: go.Link.OrientUpright,
      },
      new go.Binding('text', 'text')
    ),
    $(
      go.TextBlock, // the "to" label
      {
        textAlign: 'center',
        font: 'bold 14px sans-serif',
        stroke: '#1967B3',
        segmentIndex: -1,
        segmentOffset: new go.Point(NaN, NaN),
        segmentOrientation: go.Link.OrientUpright,
      },
      new go.Binding('text', 'toText')
    )
  )

  myDiagram.model = $(go.GraphLinksModel, {
    nodeDataArray: tabViewList.value,
    linkDataArray: tabRelView.value,
  })
}
const showLink = () => {
  curActive.value = 'relation'
  if (myDiagram) {
    myDiagram.div = null
    myDiagram = {}
  }
  title.value = sourceData.code + ' ' + sourceData.name + '__关联的对象'
  tabRelView.value = []
  tabViewList.value = []
  apiGetEr(sourceData.id).then((res) => {
    showNodes(res)
  })
}
const showLinkMe = () => {
  curActive.value = 'link'
  if (myDiagram) {
    myDiagram.div = null
    myDiagram = {}
  }
  title.value = '引用__' + sourceData.code + ' ' + sourceData.name + '__的对象'
  tabRelView.value = []
  tabViewList.value = []
  apiGetLinkMeEr(sourceData.id).then((res) => {
    showNodes(res)
  })
}
const wrapperNode = (res) => {
  var mainItems = []
  if (res.attributesVOList && res.attributesVOList.length > 0) {
    mainItems = res.attributesVOList.map((val) => {
      return {
        name: val.code + ' ' + val.name,
        isKey: val.code === 'id',
        figure: '',
        color: '#1c446f',
      }
    })
  }
  tabViewList.value.push({
    key: res.code + ' ' + res.name,
    items: mainItems,
  })
  if (res.linkBuss) {
    res.linkBuss.forEach((val) => {
      var linkItems = []
      if (val.attributesVOList && val.attributesVOList.length > 0) {
        linkItems = val.attributesVOList.map((vo) => {
          return {
            name: vo.code + ' ' + vo.name,
            isKey: vo.code === 'id',
            figure: '',
            color: '#1c446f',
          }
        })
      }
      tabViewList.value.push({
        key: val.code + ' ' + val.name,
        items: linkItems,
      })
      tabRelView.value.push({
        from: res.code + ' ' + res.name,
        to: val.code + ' ' + val.name,
        text: '',
        toText: '',
      })
    })
  }
}

const dialogClose = () => {
  visible.value = false
  // if (myDiagram) {
  //   myDiagram.isValid = false
  //   myDiagram.model = null
  //   myDiagram.toolManager = null
  //   myDiagram.diagramDiv = null
  //   myDiagram = null
  // }
  myDiagram = {}
}

defineExpose({
  show,
})
</script>

<style lang="scss" scoped></style>
